#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   mixins.py
@Time    :   2024/01/30 17:31:52
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib

from typing import Any
from django.db.models import QuerySet

from .models import Book,Store, StoreBookSubscription


class BookViewMixin:
    request: Any
    
    def get_queryset(self) -> QuerySet:
        """
        获取查询集。如果当前请求的用户是超级用户，则返回所有书籍对象的查询集，
        否则，返回当前请求用户拥有的所有书籍对象的查询集。
        :return: Book对象的查询集
        """
        if hasattr(self.context.request, "user") and self.context.request.user.is_superuser:
            return Book.objects.all()
        return Book.objects.filter(created_by_id=self.context.request.user)



class StoreViewMixin:
    request: Any

    def get_queryset(self) -> QuerySet:
        """
        获取查询集。

        如果当前请求的用户是超级用户，则返回所有商店对象的查询集,
        否则，返回当前请求用户拥有的所有商店对象的查询集。

        :return: Store对象的查询集
        """
        if hasattr(self.context.request, "user") and self.context.request.user.is_superuser:
            return Store.objects.all()
        return Store.objects.filter(owner_id=self.context.request.user)


class StoryBookQuerySetMixin:
    request: Any


def get_queryset(self):
    """
    获取查询集。如果用户是超级用户,则返回所有StoreBookSubscription对象,
    否则返回与当前用户关联的StoreBookSubscription对象。

    :return: StoreBookSubscription对象的查询集
    """
    if hasattr(self.context.request, "user") and self.context.request.user.is_superuser:
        return StoreBookSubscription.objects.select_related(
            "store_book", "subscriber"
        ).all()
    return StoreBookSubscription.objects.select_related(
        "store_book", "subscriber"
    ).filter(store_book__store__owner=self.context.request.user)
